import regEmailApi from '@/api/user/regEmailApi'
import regPhoneApi from '@/api/user/regPhoneApi'
import { getAppNav } from '@/App'
import CEmailOrPhoneCode from '@/components/user/CEmailOrPhoneCode'
import IRegByPhoneForm from '@/model/form/user/IRegByPhoneForm'
import IRegEmailForm from '@/model/form/user/IRegisterForm'
import IUserCenterUpdatePhoneForm from '@/model/form/userCenter/IUserCenterUpdatePhoneForm'
import IResVO from '@/model/vo/common/IResVO'
import { useAppSelector } from '@/store'
import { ToastError, ToastSuccess } from '@/util/CommonUtil'
import { passwordRSAEncrypt, RSAEncryptPro } from '@/util/UserUtil'
import Validator, { validate } from '@/util/Validator'
import { BaseFormApi } from '@douyinfe/semi-foundation/lib/es/form/interface'
import { Button, Form } from '@douyinfe/semi-ui'
import { ReactFieldError } from '@douyinfe/semi-ui/lib/es/form'
import { AxiosResponse } from 'axios'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'
import LoginRegisterBase from '../components/LoginRegisterBase/LoginRegisterBase'

export default function Register() {
  const [loading, setLoading] = useState(false)

  const formApi = useRef<BaseFormApi>()

  const rsaPublicKey = useAppSelector((state) => state.common.rsaPublicKey)

  const [codeText, setCodeText] = useState('获取验证码')

  const timer = useRef<NodeJS.Timer>()

  useEffect(() => {
    return () => {
      clearTimer()
    }
  }, [timer])

  function clearTimer() {
    if (timer.current) {
      clearInterval(timer.current)
    }
  }

  return (
    <LoginRegisterBase name="注册">
      <Form
        disabled={loading}
        getFormApi={(api) => (formApi.current = api)}
        className="w-300"
        onSubmit={(form) => {
          if (loading) return
          submitClick(form as IRegEmailForm, setLoading, rsaPublicKey)
        }}
        onSubmitFail={(errors: Record<string, ReactFieldError>) => {
          errors.code ? ToastError(errors.code as string) : null
        }}
      >
        <Form.Input
          field="emailOrPhone"
          placeholder="邮箱/手机号"
          noLabel
          validate={Validator['emailOrPhoneValidate']}
          showClear
        />
        <Form.Input
          field="password"
          placeholder="密码"
          noLabel
          validate={Validator['passwordValidate']}
          showClear
          mode="password"
        />
        <CEmailOrPhoneCode
          noLabel
          setCodeText={setCodeText}
          timer={timer}
          clearTimer={clearTimer}
          codeText={codeText}
          loading={loading}
          sendCodeType={3}
        ></CEmailOrPhoneCode>
        <Button
          block
          type="warning"
          size="large"
          loading={loading}
          htmlType="submit"
          className="m-t-10"
        >
          注 册
        </Button>
        <Button
          disabled={loading}
          block
          className="m-t-10"
          onClick={() => getAppNav()('/login')}
        >
          去登录
        </Button>
      </Form>
    </LoginRegisterBase>
  )
}

// 点击提交按钮
function submitClick(
  form: IRegEmailForm | IRegByPhoneForm,
  setLoading: Dispatch<SetStateAction<boolean>>,
  rsaPublicKey: string
) {
  setLoading(true) // 设置 loading状态

  const date = new Date()
  form.origPassword = RSAEncryptPro(form.password, rsaPublicKey, date)
  form.password = passwordRSAEncrypt(form.password, rsaPublicKey, date)

  if (validate.email.validate(form.emailOrPhone)) {
    doReg(regEmailApi({ ...form, email: form.emailOrPhone }), setLoading)
  } else if (validate.phone.validate(form.emailOrPhone)) {
    doReg(regPhoneApi({ ...form, phone: form.emailOrPhone }), setLoading)
  } else {
    ToastError('暂不支持此账号类型：' + form.emailOrPhone)
  }
}

// 执行注册
function doReg(
  api: Promise<AxiosResponse<IResVO<string>, any>>,
  setLoading: Dispatch<SetStateAction<boolean>>
) {
  api
    .then((res) => {
      ToastSuccess(res.data.msg)
      // 跳转到登录页
      getAppNav()('/')
    })
    .catch((e) => {
      setLoading(false) // 取消 loading状态
    })
}
